// HTML到Markdown转换函数
function htmlToMarkdown(html) {
  // 创建临时DOM元素来解析HTML
  console.log(html);
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;
  
  let result = convertElement(tempDiv);
  
  // 清理多余的换行
  result = result.replace(/\n{3,}/g, '\n\n'); // 将3个或更多连续换行替换为2个
  result = result.replace(/^\n+|\n+$/g, ''); // 去除开头和结尾的换行
  
  // 移除列表项后面多余的换行
  result = result.replace(/(^\s*[-*+]\s+.*)\n\n/gm, '$1\n');
  result = result.replace(/(^\s*\d+\.\s+.*)\n\n/gm, '$1\n');
  
  // 移除标题行中的链接，如果标题内容为空则保留链接文本
  result = result.replace(/^(#+\s*)(.*?)\s*\[([^\]]+)\]\([^\)]+\)/gm, (match, prefix, content, linkText) => {
    // 如果标题内容为空或只有空格，使用链接文本作为标题
    return content.trim() ? prefix + content : prefix + linkText;
  });
  
  return result;
}

function convertElement(element, listContext = null) {
  let markdown = '';
  
  for (let node of element.childNodes) {
    if (node.nodeType === Node.TEXT_NODE) {
      // 文本节点
      markdown += node.textContent;
    } else if (node.nodeType === Node.ELEMENT_NODE) {
      // 元素节点
      const tagName = node.tagName.toLowerCase();
      
      switch (tagName) {
        case 'h1':
          const h1Content = convertElement(node);
          markdown += `# ${h1Content}\n\n`;
          break;
        case 'h2':
          const h2Content = convertElement(node);
          markdown += `## ${h2Content}\n\n`;
          break;
        case 'h3':
          const h3Content = convertElement(node);
          markdown += `### ${h3Content}\n\n`;
          break;
        case 'h4':
          const h4Content = convertElement(node);
          markdown += `#### ${h4Content}\n\n`;
          break;
        case 'h5':
          const h5Content = convertElement(node);
          markdown += `##### ${h5Content}\n\n`;
          break;
        case 'h6':
          const h6Content = convertElement(node);
          markdown += `###### ${h6Content}\n\n`;
          break;
        case 'p':
          const pContent = convertElement(node);
          markdown += `${pContent}\n\n`;
          break;
        case 'br':
          markdown += '  \n';
          break;
        case 'strong':
        case 'b':
          const strongContent = convertElement(node);
          markdown += `**${strongContent}**`;
          break;
        case 'em':
        case 'i':
          const emContent = convertElement(node);
          markdown += `*${emContent}*`;
          break;
        case 'code':
          const codeContent = convertElement(node);
          markdown += `${codeContent}`;
          break;
        case 'pre':
          const preContent = node.textContent || node.innerText || '';
          markdown += `\n\`\`\`\n${preContent}\n\`\`\`\n\n`;
          break;
        case 'a':
          const href = node.getAttribute('href') || '';
          const linkContent = convertElement(node);
          markdown += `[${linkContent}](${href})`;
          break;
        case 'img':
          let src = node.getAttribute('src') || '';
          const alt = node.getAttribute('alt') || '';
          
          // 移除src地址中的反斜杠
          src = src.replace(/\\/g, '');
          
          // 如果是相对路径，转换为绝对路径
          if (src && !src.startsWith('http://') && !src.startsWith('https://') && !src.startsWith('data:')) {
            // 获取当前页面的域名和协议
            const currentUrl = new URL(window.location.href);
            const baseUrl = `${currentUrl.protocol}//${currentUrl.host}`;
            
            // 处理相对路径
            if (src.startsWith('/')) {
              // 绝对路径（相对于域名根目录）
              src = baseUrl + src;
            } else if (src.startsWith('./') || !src.startsWith('/')) {
              // 相对路径（相对于当前页面）
              const currentPath = currentUrl.pathname.substring(0, currentUrl.pathname.lastIndexOf('/') + 1);
              src = baseUrl + currentPath + src.replace('./', '');
            }
          }
          
          markdown += `![${alt}](${src})`;
          break;
        // case 'svg':
        //   // 处理SVG元素
        //   const svgAlt = node.getAttribute('alt') || node.getAttribute('title') || 'SVG图片';
          
        //   // 将SVG转换为data URL
        //   const svgString = new XMLSerializer().serializeToString(node);
        //   const svgDataUrl = `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svgString)))}`;
          
        //   markdown += `![${svgAlt}](${svgDataUrl})`;
        //   break;
        case 'ul':
          const ulContent = convertElement(node, { type: 'ul', index: 0 });
          markdown += ulContent + '\n';
          break;
        case 'ol':
          const olContent = convertElement(node, { type: 'ol', index: 0 });
          markdown += olContent + '\n';
          break;
        case 'li':
          const liContent = convertElement(node);
          if (listContext && listContext.type === 'ol') {
            listContext.index++;
            markdown += `${listContext.index}. ${liContent}\n`;
          } else {
            markdown += `- ${liContent}\n`;
          }
          break;
        case 'blockquote':
          const blockContent = convertElement(node);
          const lines = blockContent.split('\n');
          markdown += lines.map(line => line.trim() ? `> ${line}` : '>').join('\n') + '\n\n';
          break;
        case 'table':
          markdown += convertTable(node);
          break;
        case 'div':
        case 'span':
          const divContent = convertElement(node, listContext);
          markdown += divContent;
          break;
        default:
          const defaultContent = convertElement(node, listContext);
          markdown += defaultContent;
      }
    }
  }
  
  return markdown;
}

function convertTable(table) {
  let markdown = '\n';
  const rows = table.querySelectorAll('tr');
  
  rows.forEach((row, index) => {
    const cells = row.querySelectorAll('td, th');
    const cellContents = Array.from(cells).map(cell => cell.textContent.trim());
    
    markdown += '| ' + cellContents.join(' | ') + ' |\n';
    
    // 添加表头分隔符
    if (index === 0) {
      markdown += '| ' + cellContents.map(() => '---').join(' | ') + ' |\n';
    }
  });
  
  return markdown + '\n';
}

// 获取选中内容的HTML
function getSelectionHtml() {
  const selection = window.getSelection();
  if (selection.rangeCount === 0) return '';
  
  const range = selection.getRangeAt(0);
  const container = document.createElement('div');
  container.appendChild(range.cloneContents());
  
  return container.innerHTML;
}

// 复制到剪贴板的函数
async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch (err) {
    // 降级方案
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.opacity = '0';
    document.body.appendChild(textArea);
    textArea.select();
    const success = document.execCommand('copy');
    document.body.removeChild(textArea);
    return success;
  }
}

// 显示通知的函数
function showNotification(message, type = 'success') {
  const notification = document.createElement('div');
  notification.style.cssText = `
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 12px 20px;
    background: ${type === 'success' ? '#4caf50' : '#f44336'};
    color: white;
    border-radius: 6px;
    z-index: 10000;
    font-size: 14px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  `;
  notification.textContent = message;
  document.body.appendChild(notification);
  
  setTimeout(() => {
    if (notification.parentNode) {
      notification.parentNode.removeChild(notification);
    }
  }, 3000);
}

// 监听来自background script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === 'convertToMarkdown') {
    const selectionHtml = getSelectionHtml();
    
    if (selectionHtml) {
      const markdown = htmlToMarkdown(selectionHtml);
      
      // 检查是否来自右键菜单（通过selectionText判断）
      if (request.selectionText) {
        // 右键菜单：直接复制到剪贴板
        copyToClipboard(markdown).then(success => {
          if (success) {
            showNotification('Markdown 已复制到剪贴板！');
          } else {
            showNotification('复制失败，请重试', 'error');
          }
        });
      } else {
        // 弹窗：显示结果页面
        chrome.runtime.sendMessage({
          action: 'showMarkdown',
          markdown: markdown,
          originalHtml: selectionHtml
        });
      }
    } else {
      showNotification('请先选择要转换的内容', 'error');
    }
  } else if (request.action === 'copyMarkdownToClipboard') {
    copyToClipboard(request.markdown).then(success => {
      if (success) {
        showNotification('Markdown 已复制到剪贴板！');
      } else {
        showNotification('复制失败，请重试', 'error');
      }
    });
  } else if (request.action === 'checkSelection') {
    const selection = window.getSelection();
    const hasSelection = selection.toString().length > 0;
    sendResponse({ hasSelection: hasSelection });
  }
});

// 检查选择状态的函数
function hasTextSelection() {
  const selection = window.getSelection();
  return selection.toString().length > 0;
}